package com.huiminpay.transaction.Controller;

import com.alibaba.fastjson.JSON;
import com.huiminpay.merchant.api.AppService;
import com.huiminpay.merchant.common.cache.util.*;
import com.huiminpay.merchant.dto.AppDTO;
import com.huiminpay.paymentagent.api.dto.PaymentResponseDTO;
import com.huiminpay.transaction.api.TransactionService;
import com.huiminpay.transaction.convert.PayOrderConvert;
import com.huiminpay.transaction.dto.PayOrderDTO;
import com.huiminpay.transaction.vo.OrderConfirmVO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Controller
public class PayController {
    @Reference
    AppService appService;
    @Autowired
    TransactionService transactionService;
    //扫描二维码后进入支付入口
    // 支付入口
    @RequestMapping(value = "/pay-entry/{ticket}")
    public String payEntry(@PathVariable("ticket") String ticket, HttpServletRequest request) {
//        //将ticket的base64还原
//        String ticketStr = EncryptUtil.decodeUTF8StringBase64(ticket);
//        //将ticket（json）转成对象
//        PayOrderDTO order = JSON.parseObject(ticketStr, PayOrderDTO.class);
//        //将对象转成url格式
//        String params = null;
//        try {
//            params = ParseURLPairUtil.parseURLPair(order);
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
//        return "forward:/pay-page?" + params;
//    }
            try {
                //将ticket的base64还原
                String ticketStr = EncryptUtil.decodeUTF8StringBase64(ticket);
                //将ticket（json）转成对象
                PayOrderDTO order = JSON.parseObject(ticketStr, PayOrderDTO.class);
                // 将对象转成url格式:String url = toParamsString(order);
                BrowserType browserType = BrowserType.valueOfUserAgent(request.getHeader("user‐agent"));
                switch (browserType) {
                    case ALIPAY: //直接跳转收银台pay.html //将对象转成url格式
                        return "forward:/pay-page?" + ParseURLPairUtil.parseURLPair(order);
                    case WECHAT: //获取授权码(待实现)     //将对象转成url格式
                        return "forward:/pay-page?" + ParseURLPairUtil.parseURLPair(order);
                    default:
                }
            }catch (Exception e){
                e.printStackTrace();
                log.error(e.getMessage(),e);
            }
            return "forward:/pay_error";
}
    // 使用支付宝为门店下单支付
    @ApiOperation("支付宝门店下单付款")
    @PostMapping("/createAliPayOrder")
    public void createAlipayOrderForStore(OrderConfirmVO orderConfirmVO, HttpServletRequest request, HttpServletResponse response) throws Exception{
        //将vo转换为dto
        PayOrderDTO payOrderDTO = PayOrderConvert.INSTANCE.vo2dto(orderConfirmVO);
        String appId = payOrderDTO.getAppId();//获取应用id
        //根据应用id查询应用信息
        AppDTO appDTO = appService.getAppById(appId);
        payOrderDTO.setMerchantId(appDTO.getMerchantId()); //设置商户编号
        //将前端输入的 元转成分
        String yuan = orderConfirmVO.getTotalAmount();
        String fen = AmountUtil.changeY2F(yuan);
        payOrderDTO.setTotalAmount(Integer.parseInt(fen));
        //客户端ip
        payOrderDTO.setClientIp(IPUtil.getIpAddr(request));
        //调用TranactionService中的方法实现下单
        PaymentResponseDTO<String> responseDTO = transactionService.submitOrderByAli(payOrderDTO);
        String form = responseDTO.getContent();
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(form);
        response.getWriter().flush();
        response.getWriter().close();
    }
}
